package xiaojian.toolkit.jms;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.Transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.util.ByteUtils;

public class StcMessageListener implements MessageListener {

	private static final Logger logger = LoggerFactory
			.getLogger(StcMessageListener.class);

	private Transformer<byte[], Object> transformer;
	private Closure messageDispatch;

	/**
	 * @return the messageDispatch
	 */
	public Closure getMessageDispatch() {
		return messageDispatch;
	}

	/**
	 * @param messageDispatch
	 *            the messageDispatch to set
	 */
	public void setMessageDispatch(Closure messageDispatch) {
		this.messageDispatch = messageDispatch;
	}

	/**
	 * @return the decoder
	 */
	public Transformer<byte[], Object> getTransformer() {
		return transformer;
	}

	/**
	 * @param decoder
	 *            the decoder to set
	 */
	public void setTransformer(Transformer<byte[], Object> transformer) {
		this.transformer = transformer;
	}

	public void onMessage(Message msg) {
		if (msg instanceof BytesMessage) {
			BytesMessage bytesMessage = (BytesMessage) msg;
			byte[] content = null;
			try {
				content = new byte[(int) bytesMessage.getBodyLength()];
			} catch (JMSException exception) {
				logger.error(
						"Receive bytes message, but cannot get body's length.",
						exception);
				return;
			}

			try {
				bytesMessage.readBytes(content);
			} catch (JMSException exception) {
				logger.error("Receive content fail.", exception);
				return;
			}

			if (content == null || content.length == 0) {
				logger.error("Receive bytes message, but body is empty");
				return;
			}

			logger.debug("body lenth[" + content.length + "], row value:\r\n"
					+ ByteUtils.bytesAsHexString(content, 1024));

			Object obj = null;
			try {
				obj = transformer.transform(content);
			} catch (Exception exception) {
				logger.error("Cannot get message's object.", exception);
				return;
			}
			logger.info("onMessage:" + obj);
			messageDispatch.execute(obj);

			return;
		}

		logger.warn("Receive invalid message[" + msg + "].");
	}

}
